<template>
  <view class="container">
    <view v-if="isLogin" class="margin text-center">
      自动登录中...
    </view>
    <view v-else>
      <view class="margin">
        <view class="margin text-xl text-bold">
          手机号验证码登录
        </view>
        <view class="margin margin-top-xl solids radius bg-gray padding-left padding-tb-sm">
          <input placeholder="请输入手机号" name="input" type="number" placeholder-class="text-lg" style="height: 100%" @blur="inputPhone"/>
        </view>
        <view class="margin flex align-center justify-between">
          <view class="solids radius bg-gray padding-left padding-tb-sm flex-treble">
            <input placeholder="请输入验证码" name="input" type="number" placeholder-class="text-lg" @blur="inputCode"/>
          </view>
          <view>
            <button class="cu-btn bg-xzg margin-left-sm" @click="sendBindPhoneCode" v-if="!sendingSms">获取验证码</button>
            <view v-else>
              <button class="cu-btn bg-xzg margin-left-sm line-xzg" disabled>
                <text class="text-black">{{leftSendingTime}}秒后重试</text>
              </button>
            </view>
          </view>
        </view>
        <view class="margin margin-top-xl flex align-center justify-center">
          <button class="cu-btn round lg bg-xzg" style="width: 100%" @click="bindAgentPhoneAndLogin">登录</button>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import {request, showToast, startLogin} from "../../utils/request";

export default {
  name: 'login',
  data() {
    return {
      isLogin: false,
      openId: '',
      avatarUrl: '',
      phone: '',
      code: '',
      sendingSms: false,
      leftSendingTime: 60
    }
  },
  onLoad() {
    // todo 测试
    // this.setCookie("agent-init", "true")
    // this.setCookie("agent-openId", "o2JoM1Yaf8c_AOg4rza3tHmoVpWg")
    // this.setCookie("agent-avatarUrl", "https://thirdwx.qlogo.cn/mmopen/vi_32/PiajxSqBRaELOHK7yWe9r38aiaadwGlcqMVTR8eVVPfiaSZrs5cOsqfWoS5MZzAnZicnSc3EJEibW1YE6gVawpArUmAcRmfkMa7nSBXEZCPILxZjfhbTsr3BLHQ/132")
    this.checkLoginStatus()
  },
  methods: {
    loginSuccess() {
      uni.reLaunch({
        url: '/pages/index/index'
      })
    },
    checkLoginStatus() {
      let token = this.getCookie("agent-token")
      if (token && token.length > 0) {
        console.log("ok")
        uni.setStorageSync('agent-token', token)
        this.loginSuccess()
        return
      }
      let initLogin = this.getCookie("agent-init")
      if (!initLogin || initLogin !== "true") {
        startLogin()
        return;
      }
      this.openId = this.getCookie("agent-openId")
      this.avatarUrl = this.getCookie("agent-avatarUrl")
      console.log(this.phone)
      console.log(this.openId)
    },
    // 获取Cookie
    getCookie(key) {
      const cookieStr = document.cookie;
      const cookies = cookieStr.split('; ');
      for (const cookie of cookies) {
        const [cookieKey, cookieValue] = cookie.split('=');
        if (cookieKey === key) {
          return decodeURIComponent(cookieValue);
        }
      }
      return null;
    },
    sendBindPhoneCode() {
      console.log(this.phone)
      console.log(this.openId)
      request({url: '/sms/send/agent', method: 'POST', data: {phone: this.phone, openId: this.openId}}).then(res => {
        showToast('验证码发送成功')
        this.sendingSms = true
        // 开始倒计时
        this.leftSendingTime = 60
        let _this = this
        this.timer = setInterval(() => {
          _this.leftSendingTime--
          if (_this.leftSendingTime <= 0) {
            clearInterval(_this.timer)
            _this.sendingSms = false
            _this.leftSendingTime = 60
          }
        }, 1000)
      })
    },
    bindAgentPhoneAndLogin() {
      request({url: '/agent/bind', method: 'POST', data: {code: this.code, openId: this.openId, avatarUrl: this.avatarUrl, phone: this.phone}}).then(res => {
        console.log(res)
        if (!res) {
          showToast('登录失败，请重试')
          return
        }
        this.setCookie("agent-token", res)
        this.removeCookie("agent-openId")
        this.removeCookie("agent-avatarUrl")
        this.checkLoginStatus()
      })
    },
    // 设置Cookie
    setCookie(key, value, days = 7, path = '/') {
      const expires = new Date();
      expires.setTime(expires.getTime() + days * 10 * 60 * 60 * 1000);
      document.cookie = `${key}=${encodeURIComponent(value)};expires=${expires.toUTCString()};path=${path}`;
    },
    removeCookie(key, path = '/') {
      document.cookie = `${key}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${path}`;
    },
    inputPhone(e) {
      this.phone = e.detail.value
    },
    inputCode(e) {
      this.code = e.detail.value
    }
  }
}
</script>
<style>
body {
  background-color: #ffffff;
}

.container {
  position: fixed;
  justify-content: center;  /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  top: 25%;
  width: 100%;
}
</style>